const { ccclass, property } = cc._decorator;

@ccclass
export default class Launch extends cc.Component {

    @property(cc.Node)
    display: cc.Node = null;

    @property(cc.Prefab)
    itemPrefab: cc.Prefab = null;

    @property(cc.ScrollView)
    scrollView: cc.ScrollView = null;

    @property(cc.Node)
    self: cc.Node = null;

    ITEM_HEIGHT: number = 100;
    NUM_PER_PAGE: number = 5;

    //当前渲染的rank数据
    nowRankData: Array<any>;
    //群排行数据
    groupRankData: Array<any>;
    //好友排行数据
    friendRankData: Array<any>;

    cells: Array<cc.Node>;

    selfScore: number;
    selfUrl: string;
    start() {

        //占位资源，方便主域定位
        cc.find('Canvas/back').active = false;
        cc.find('Canvas/btnGroup').active = false;

        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            //初始化自己分数
            wx.getUserCloudStorage({
                keyList: ['score'],
                success: res => {
                    this.selfScore = res.KVDataList.length > 0 ? res.KVDataList[0]['value'] : 0;
                }
            })

            //接收主域命令
            wx.onMessage(data => {
                switch (data.cmd) {
                    case 'init':
                        this.selfUrl = data.url;
                        break;
                    case 'set':
                        this.report(data.score);
                        break;
                    case 'friend':
                        this.node.active = true;
                        this.getFriendCloudStorage();
                        break;
                    case 'group':
                        this.node.active = true;
                        this.getGroupCloudStorage(data.shareTicket);
                        break;
                    case 'hide':
                        this.node.active = false;
                        break;
                }
            });
        }

        //预先创建n+1个renderItem
        this.cells = [];
        for (let i: number = 0; i < this.NUM_PER_PAGE + 1; i++) {
            let cell: cc.Node = cc.instantiate(this.itemPrefab);
            this.display.addChild(cell);
            this.cells.push(cell);
        }

        //监听scrollview事件
        this.scrollView.node.on('scrolling', this.scroll.bind(this), this);

        this.node.active = false;
    }

    //上报分数
    report(score: number) {
        if (score > this.selfScore) {
            wx.setUserCloudStorage({
                KVDataList: [{
                    'key': 'score',
                    'value': `${score}`
                }],
                success: res => {
                    this.selfScore = score;
                }
            })
        }
    }

    //获取好友排行数据
    getFriendCloudStorage() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.getFriendCloudStorage({
                keyList: ['score'],
                success: res => {
                    this.friendRankData = res.data;
                    this.nowRankData = this.friendRankData;

                    this.nowRankData.sort((a, b) => {
                        return b.KVDataList[0]['value'] - a.KVDataList[0]['value'];
                    })

                    this.drawRankList();
                }
            });
        }
    }

    //获取群排行数据
    getGroupCloudStorage(shareTicket: string) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME && shareTicket) {
            wx.getGroupCloudStorage({
                shareTicket: shareTicket,
                keyList: ['score'],
                success: res => {
                    this.groupRankData = res.data;
                    this.nowRankData = this.groupRankData;

                    this.nowRankData.sort((a, b) => {
                        return b.KVDataList[0]['value'] - a.KVDataList[0]['value'];
                    })

                    this.drawRankList();
                }
            });
        } else {
            this.nowRankData = [];
            this.drawRankList();
        }
    }

    drawRankList() {
        let hasSelf: boolean = false;
        for (let i: number = 0; i < this.nowRankData.length; i++) {
            if (this.nowRankData[i].avatarUrl == this.selfUrl) {
                this.drawSelf(this.nowRankData[i], i);
                hasSelf = true;
            }
        }

        if (!hasSelf) {
            this.self.active = false;
        }

        this.display.y = 0;
        this.display.height = this.nowRankData.length * this.ITEM_HEIGHT;
        this.scroll();
    }

    drawSelf(item, index) {
        this.self.active = true;

        this.self.getChildByName('tfNo').getComponent(cc.Label).string = `${index + 1}`;
        this.createImage(this.self.getChildByName('photo').getComponent(cc.Sprite), item.avatarUrl);
        this.self.getChildByName('tfName').getComponent(cc.Label).string = `${item.nickname} `;
        this.self.getChildByName('tfScore').getComponent(cc.Label).string = `${item.KVDataList[0]['value']}`;
    }

    scroll(e = null) {
        let i: number;
        let startIndex: number = Math.floor(Math.max(0, this.display.y) / this.ITEM_HEIGHT);
        for (i = startIndex; i < startIndex + this.NUM_PER_PAGE + 1 && i < this.nowRankData.length; i++) {
            this.drawItem(this.nowRankData[i], i);
        }
        for (i = this.nowRankData.length; i < this.NUM_PER_PAGE + 1; i++) {
            this.cells[i].active = false;
        }
    }

    drawItem(item, index) {
        let cell: cc.Node = this.cells[index % (this.NUM_PER_PAGE + 1)];
        cell.active = true;
        cell.y = -index * 100;

        cell.getChildByName('tfNo').getComponent(cc.Label).string = `${index + 1}`;
        this.createImage(cell.getChildByName('photo').getComponent(cc.Sprite), item.avatarUrl);
        cell.getChildByName('tfName').getComponent(cc.Label).string = `${item.nickname} `;
        cell.getChildByName('tfScore').getComponent(cc.Label).string = `${item.KVDataList[0]['value']}`;
    }

    //.子域中加载图片
    createImage(sprite, url) {
        let image = wx.createImage();
        image.onload = function () {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            sprite.spriteFrame = new cc.SpriteFrame(texture);
        };
        image.src = url;
    }
}